// index.ts
// 获取应用实例
const app = getApp<IAppOption>()
import { config } from '../../utils/config';
// 使用网络默认头像（避免依赖本地images目录）
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Component({
  data: {
    motto: '请完善信息以继续',
    userInfo: {
      avatarUrl: defaultAvatarUrl, // 初始使用网络默认头像
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    menus: [
      { name: '选择AI病人', icon: '👤', url: '/pages/patients/patients' },
      { name: '病例管理', icon: '📁', url: '/pagess/cases/cases' },
      { name: '学习记录', icon: '📚', url: '/pages/records/records' },
      { name: '设置', icon: '⚙️', url: '/pages/setting/setting' }
    ]
  },

  methods: {
    // 事件处理函数
    bindViewTap() {
      wx.navigateTo({
        url: '../logs/logs',
      })
    },

    onChooseAvatar(e: any) {
      const { avatarUrl } = e.detail
      const { nickName } = this.data.userInfo
      // 选择头像后更新头像URL
      this.setData({
        "userInfo.avatarUrl": avatarUrl,
      }, () => {
        console.log('头像选择后：', {
          newAvatar: avatarUrl,
          isDifferent: avatarUrl !== defaultAvatarUrl
        })
      })
    },

    onInputChange(e: any) {
      const nickName = e.detail.value?.trim() // 去除空格
      // 输入昵称后更新状态
      this.setData({
        "userInfo.nickName": nickName,
      }, () => {
        console.log('昵称输入后：', {
          newNickname: nickName
        })
      })
    },

    getUserProfile() {
      // 兼容旧版本获取用户信息方式
      wx.getUserProfile({
        desc: '展示用户信息',
        success: (res) => {
          console.log('getUserProfile成功：', res.userInfo)
          this.setData({
            userInfo: res.userInfo
          })
        },
        fail: (err) => {
          console.log('getUserProfile失败：', err)
          wx.showToast({
            title: '获取信息失败',
            icon: 'none'
          })
        }
      })
    },

    getPhoneNumber(e: any) {
      const { code, encryptedData, iv } = e.detail;
      console.log(e.detail);
      console.log(e.detail.code);
      if (!code) {
        return wx.showToast({ title: '手机号授权失败', icon: 'none' });
      }

      const { avatarUrl, nickName } = this.data.userInfo;
      
      // 验证用户信息完整性
      if (avatarUrl === defaultAvatarUrl) {
        wx.showToast({ title: '请先选择头像', icon: 'none' });
        return;
      }
      if (!nickName?.trim()) {
        wx.showToast({ title: '请先输入昵称', icon: 'none' });
        return;
      }

      // 获取登录凭证code并调用后端接口
      wx.login({
        success: (loginRes) => {
          if (!loginRes.code) {
            wx.showToast({ title: '获取登录凭证失败', icon: 'none' });
            return;
          }

          // 调用后端登录接口
          wx.request<{
            code: number;
            msg?: string;
            data?: any;
          }>({
            url: `${config.baseUrl}/api/v1/wechat/login/`,
            method: 'POST',
            data: {
              code: loginRes.code,       // 登录凭证code
              phoneCode: code,           // 手机号授权code
              encryptedData: encryptedData,
              iv: iv,
              avatarUrl: avatarUrl,
              nickName: nickName
            },
            success: (res) => {
              if (res.data?.code === 200) {
                wx.setStorageSync('userInfo', res.data.data);
                this.setData({ hasUserInfo: true });
                wx.showToast({ title: '登录成功', icon: 'success' });
              } else {
                wx.showToast({ title: res.data?.msg || '登录失败', icon: 'none' });
              }
            },
            fail: () => {
              wx.showToast({ title: '网络请求失败', icon: 'none' });
            }
          });
        },
        fail: () => {
          wx.showToast({ title: '登录流程失败', icon: 'none' });
        }
      })
    },

    navigateToPage(e: any) {
      const url = e.currentTarget.dataset.url
      wx.navigateTo({ url })
    }
  },
})